﻿using System;
using System.Runtime.InteropServices;

namespace JipPlayer_2._0
{
    public class WLMStatusChanger
    {
        static string windowclass = "MsnMsgrUIManager";

        [DllImport("user32", EntryPoint = "SendMessageA")]
        private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam);

        [DllImport("user32", EntryPoint = "FindWindowExA")]
        private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2);

        private const short WM_COPYDATA = 74;

        private struct COPYDATASTRUCT
        {
            public int dwData;
            public int cbData;
            public int lpData;
        }

        private class WindowNotFoundException : InvalidOperationException { }

        public enum MessageCategory
        {
            Music
        };

        private static int VarPtr(object e)
        {
            GCHandle GC = GCHandle.Alloc(e, GCHandleType.Pinned);
            int gc = GC.AddrOfPinnedObject().ToInt32();
            GC.Free();
            return gc;
        }

        public static void SendMSNMessage(bool enable, MessageCategory category, string liedje, string Artiest)
        {
            SendMSNMessage(enable, category, liedje, Artiest, windowclass);
        }

        public static void SendMSNMessage(bool enable, MessageCategory category, string liedje, string Artiest, string windowclass)
        {
            
            string buffer = "\\0" + category.ToString() + "\\0" + (enable ? "1" : "0") + "\\0{1} - {0}\\0" + liedje + "\\0" + Artiest + " ~ JipPlayer " + System.Windows.Forms.Application.ProductVersion + " (Dev Edition)" + "\\0\\0\\0\0";
            int handle = 0;

            COPYDATASTRUCT data;
            data.dwData = 0x0547;
            data.lpData = VarPtr(buffer);
            data.cbData = buffer.Length * 2;

            handle = FindWindowEx(0, handle, windowclass, null);
            if (handle > 0)
                SendMessage(handle, WM_COPYDATA, 0, VarPtr(data));
            else
                throw new WindowNotFoundException();
        }
    }
}